/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.business.ejb;

import han.bifang.business.dao.StatBusDao;
import han.bifang.business.dao.StatDetailLogDao;
import han.bifang.business.dao.StatServiceDao;
import han.bifang.common.entity.EntityConstants;
import han.bifang.common.entity.SoaStatBus;
import han.bifang.common.entity.SoaStatDetailLog;
import han.bifang.common.entity.SoaStatService;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import javax.transaction.UserTransaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import v1.statistics.web.bifang.han.StatLogDocument;

/**
 * @Author kent
 */

@MessageDriven(mappedName = "han.bifang.statistics.Queue", name = "StatMDB", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })
@TransactionManagement(value = TransactionManagementType.BEAN)
public class StatMDB implements MessageListener {

	private static Log logger = LogFactory.getLog(StatMDB.class);
	public void onMessage(Message arg0) {
		UserTransaction utx = null;
		try {
			InitialContext ctx = new InitialContext();
			utx = (UserTransaction) ctx
					.lookup("javax.transaction.UserTransaction");
			utx.begin();
			TextMessage txt = (TextMessage) arg0;
			logger.info(txt.getText());
			String xml = txt.getText();
			StatLogDocument doc = StatLogDocument.Factory.parse(xml);
			if (doc.validate()) {
				SoaStatDetailLog log = new SoaStatDetailLog();
				log.setBusCode(doc.getStatLog().getBusCode());
				log.setLogId(doc.getStatLog().getMessageLogId());
				log.setRequestId(doc.getStatLog().getRequestId());

				log.setCallTime(Long.parseLong(doc.getStatLog()
						.getRequestTime()));
				if (doc.getStatLog().getResponseTime() != null) {
					log.setResponseTime((int)(Long.valueOf(doc
							.getStatLog().getResponseTime()) - Long.valueOf(doc
							.getStatLog().getRequestTime())));
				}
				log.setServiceCode(doc.getStatLog().getServiceCode());
				log.setStatus(doc.getStatLog().getStatus());
				log.setVersion(doc.getStatLog().getVersion());
				
				//retry record is not a normal request, user can see it in log detail.
				if(!doc.getStatLog().getIsRetry())
					StatDetailLogDao.createStatLog(log);
				
				SoaStatBus bus = StatBusDao.getStatBus(log.getBusCode());
				bus.setTotalRequest(bus.getTotalRequest() + 1);
				if (log.getStatus().equals(EntityConstants.STATUS_OK)) {
					bus.setSuccessRequest(bus.getSuccessRequest() + 1);
				}
				StatBusDao.modifyStatBus(bus);

				SoaStatService ser = StatServiceDao.getStatService(log
						.getServiceCode(), log.getVersion());
				ser.setTotalRequest(ser.getTotalRequest() + 1);
				if (log.getStatus().equals(EntityConstants.STATUS_OK)) {
					ser.setSuccessRequest(ser.getSuccessRequest() + 1);

					if (log.getResponseTime() > ser.getMaxResponseTime()) {
						ser.setMaxResponseTime(log.getResponseTime());
					}
					if (ser.getMinResponseTime() == 0
							|| ser.getMinResponseTime() > log.getResponseTime()) {
						ser.setMinResponseTime(log.getResponseTime());
					}
					ser.setTotalResponseTime(ser.getTotalResponseTime()
							+ log.getResponseTime());
				}
				StatServiceDao.modifyStatService(ser);

			} else {
				throw new Exception("StatLog xml format invalid!");
			}
			utx.commit();
		} catch (Exception e) {
			
			logger.error("StatMDB.onMessage()", e);
			try {
				if (utx != null)
					utx.rollback();
			} catch (Exception e1) {
				// TODO: handle exception
			}

		}

	}
}
